/* vim: set expandtab shiftwidth=4:
   -*- mode: c++; c-basic-offset: 4; indent-tabs-mode: nil -*-
  
  DynamicArray
  ************
  Copyright (C) 2003 Wesley Crossman (wesley_crossman@yahoo.com)

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation; either version 2 of the License, or
  (at your option) any later version.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

#ifndef DYNAMICARRAY_H
#define DYNAMICARRAY_H

#include <vector>
#include <assert.h>
#include <iostream>

template < class T >
class DynamicArray {
protected:
    
    T *board;
    int w, h;
    
public:
    
    T &getEntry(int x, int y) {
        assert((x<w) && (y<h) && (x>=0) && (y>=0) && (board));
        return board[(x * h) + y];
    }
    
    void setEntry(int x, int y, const T &t) {
        assert((x<w) && (y<h) && (x>=0) && (y>=0) && (board));
        board[(x * h) + y] = t;
    }
    
    int width() {return w;}
    int height() {return h;}
    
    void setSize(int w, int h) {
        if ( (this->w != w) || (this->h != h) || (!board) ) {
            this->w = w;
            this->h = h;
            if (board) delete[] board;
            board = new T[w * h];
            assert(board);
        }
    }
    
    bool isValid(int x, int y) {return x<w && y<h && x>=0 && y>=0 && board;}

    DynamicArray &operator=(DynamicArray < T > &toCopy) {
    	setSize(toCopy.width(), toCopy.height());
        for (int x=0;x<w;x++) {
            for (int y=0;y<h;y++) {
                getEntry(x, y) = toCopy.getEntry(x, y);
            }
        }
        return *this;
    }
    
    DynamicArray(int w, int h) {
        board = (T *)0;
        this->w = 0;
        this->h = 0;
        setSize(w, h);
    }
    
    DynamicArray() {
        board = (T *)0;
        w = 0;
        h = 0;
    }
    
    DynamicArray(DynamicArray < T > &toCopy) {
        board = (T *)0;
        *this = toCopy;
    }
    
    virtual ~DynamicArray() {
        if (board) delete[] board;
    }
    
};

#endif

